<?php
/**
 * tvb log sqlite data
==================================
<appender>sqlite</appender>
<sqlite>
	<out_class>Sqlite</out_class>
	<path>/tmp</path>
	<table>logsa2222</table>
	<sufix>db</sufix>
</sqlite>
==================================
 * @author Peter Zhang
 * @version 1.0
 * @package TVBLog
*/

require_once 'TVB/Logger/Appender/Interface.php';
class TVB_Logger_Appender_Sqlite implements TVB_Logger_Appender_Interface
{
    private static $dbh;
    
    //connect to the sqlite.
    public static function connect($db_info)
    {
		$dsn = "sqlite:".$db_info['path'].'/'.date('Ymd').'.'.$db_info['sufix'];
        if(!isset(self::$dbh)){
            try {
                self::$dbh = new PDO($dsn);
				//create log table.
				self::createTable($db_info['table']);
            } catch (PDOException $e) {
				require_once 'TVB/Logger/Exception.php';
				throw new TVB_Logger_Exception('Connection failed: ' . $e->getMessage());
            }
        }
		
        return self::$dbh;
    }
    
    //create sqlite table by every day
    public static function createTable($tableName)
    {
        $sql = "CREATE TABLE IF NOT EXISTS `$tableName` (
                  `id` INTEGER PRIMARY KEY,
                  `log_category` varchar(20) NOT NULL,
                  `log_when` datetime NOT NULL,
                  `log_who` varchar(20) NOT NULL,
                  `log_level` varchar(20) NOT NULL,
                  `log_request` text NOT NULL,
                  `log_note` text NOT NULL,
                  `log_result` text NOT NULL
                ) ";
        return self::$dbh->exec($sql);
    }
    
    //implement the write function 
	//modify by william hu<william.hu@achievo.com>
    public function write($log_entity)
    {
		//get log entiry array
		$db_info = TVB_Logger_Config::get('sqlite', $log_entity->category);
		self::connect($db_info);
		$when = date('Y-m-d H:i:s', strtotime($log_entity->when));
		$sql = "INSERT INTO {$db_info['table']} (log_category, log_when, log_who, log_level, log_request, log_note, log_result) VALUES (?, ?, ?, ?, ?, ?, ?)";
		$sth = self::$dbh->prepare($sql);
		$sth->bindParam('1', $log_entity->category, PDO::PARAM_STR);
		$sth->bindParam('2', $when, PDO::PARAM_STR);
		$sth->bindParam('3', $log_entity->who, PDO::PARAM_STR);
		$sth->bindParam('4', $log_entity->level, PDO::PARAM_STR);
		$sth->bindParam('5', $log_entity->request, PDO::PARAM_STR);
		$sth->bindParam('6', $log_entity->note, PDO::PARAM_STR);
		$sth->bindParam('7', $log_entity->result, PDO::PARAM_STR);
		$ret = $sth->execute();
		if (!$ret) {
			require_once 'TVB/Logger/Exception.php';
			throw new TVB_Logger_Exception('SQL failed: ' . print_r(self::$dbh->errorInfo()));
		}
		
		//$sql1 = "SELECT * FROM ".$db_info['table'];
		//$stmt = self::$dbh->prepare($sql1);
		//$ret = $stmt->execute();
		//$rest = $stmt->fetchAll();
		//var_dump($rest);
		return true;
    }
}
?>